<template>
  <div class="farm-products">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.back()">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
          </div>
          <div class="header-center">
            <img src="https://susu-plants.oss-cn-beijing.aliyuncs.com/2025-03-04-22-13-33QQ20250304-190757.png" alt="Logo" class="logo-image">
            <h2>{{ farmName }} - 农场商品</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="content">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <h3>商品列表</h3>
                <el-button 
                  v-if="isOwner" 
                  type="primary" 
                  @click="handleAddProduct"
                >
                  <el-icon><Plus /></el-icon>
                  添加商品
                </el-button>
              </div>
            </template>
            
            <!-- 商品表格 -->
            <el-table 
              :data="products" 
              style="width: 100%"
              v-loading="loading"
            >
              <el-table-column label="商品图片" width="120">
                <template #default="scope">
                  <el-image
                    :src="getPrimaryImage(scope.row.images)"
                    fit="cover"
                    style="width: 80px; height: 80px"
                    :preview-src-list="getImageUrls(scope.row.images)"
                  />
                </template>
              </el-table-column>
              
              <el-table-column prop="name" label="商品名称" min-width="120" />
              
              <el-table-column label="分类" min-width="120">
                <template #default="scope">
                  <el-tag
                    v-for="category in scope.row.categories"
                    :key="category.category_id"
                    class="mx-1"
                    size="small"
                  >
                    {{ category.category_name }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="description" label="商品描述" min-width="200">
                <template #default="scope">
                  <el-tooltip
                    :content="scope.row.description"
                    placement="top"
                    :show-after="500"
                  >
                    <span class="description-text">{{ scope.row.description }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
              
              <el-table-column prop="price" label="价格" width="120">
                <template #default="scope">
                  <span class="price">¥{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="stock" label="库存" width="150">
                <template #default="scope">
                  <span>{{ scope.row.stock }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                    {{ scope.row.status === 1 ? '上架中' : '已下架' }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                  <el-button-group>
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleViewProduct(scope.row)"
                    >
                      查看
                    </el-button>
                    <el-button
                      v-if="isOwner"
                      type="warning"
                      size="small"
                      @click="handleEditProduct(scope.row)"
                    >
                      修改
                    </el-button>
                    <el-button
                      v-if="isOwner"
                      type="danger"
                      size="small"
                      @click="handleDeleteProduct(scope.row)"
                    >
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-main>
    </el-container>
    
    <!-- 添加商品对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加商品"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="addForm.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品描述" prop="productDescription">
          <el-input
            type="textarea"
            v-model="addForm.productDescription"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number 
            v-model="addForm.price"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="请输入商品价格"
          />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="addForm.stock"
            :min="0"
            :precision="0"
            :step="10"
            placeholder="请输入商品库存"
          />
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            class="product-uploader"
            :auto-upload="false"
            :show-file-list="true"
            :limit="5"
            accept="image/*"
            :on-change="handleImageChange"
            multiple
          >
            <template #trigger>
              <el-button type="primary">选择图片</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 jpg/png 文件，且不超过 5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryIds">
          <el-select
            v-model="addForm.categoryIds"
            placeholder="请选择商品分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item.categoryId"
              :label="item.name"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddProduct" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改库存对话框 -->
    <el-dialog
      title="修改库存"
      v-model="stockDialog.visible"
      width="400px"
      @close="handleStockDialogClose"
    >
      <div class="stock-form">
        <el-form :model="stockDialog.form" label-width="80px">
          <el-form-item label="库存数量">
            <el-input-number 
              v-model="stockDialog.form.stock" 
              :min="0"
              :step="10"
              :step-strictly="true"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateStock" :loading="stockDialog.loading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { getFarmDetail } from '@/api/farms'
import { getFarmProducts, createProduct, deleteProduct, getProductDetail, updateProductStock } from '@/api/products'
import { getAllCategories } from '@/api/categories'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const submitting = ref(false)
const farmName = ref('')
const products = ref([])
const isOwner = ref(false)

// 添加商品相关的响应式变量
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = ref({
  productName: '',
  productDescription: '',
  price: 0,
  stock: 0,
  images: [],
  categoryIds: null
})

// 表单验证规则
const addFormRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  productDescription: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  categoryIds: [
    { required: true, message: '请选择商品分类', trigger: 'change' },
    { type: 'number', message: '请选择商品分类', trigger: 'change' }
  ]
}

// 处理图片变化
const handleImageChange = (file, fileList) => {
  if (!file) {
    console.warn('文件对象为空')
    return false
  }

  // 检查文件大小
  if (!file.raw) {
    file = { ...file, raw: file }
  }

  if (file.raw && file.raw.size > 5 * 1024 * 1024) {
    ElMessage.warning('图片大小不能超过 5MB')
    return false
  }

  // 检查文件类型
  const fileType = file.raw ? file.raw.type : file.type
  if (!fileType || !fileType.startsWith('image/')) {
    ElMessage.warning('只能上传图片文件')
    return false
  }
  
  // 更新图片列表
  if (fileList) {
    addForm.value.images = fileList.map(f => f.raw || f)
  }
  return true
}

// 添加商品
const handleAddProduct = () => {
  addForm.value = {
    productName: '',
    productDescription: '',
    price: 0,
    stock: 0,
    images: [],
    categoryIds: null
  }
  addDialogVisible.value = true
}

// 提交添加商品
const submitAddProduct = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    submitting.value = true
    
    const farmId = route.params.farmId
    await createProduct(farmId, addForm.value)
    
    ElMessage.success('添加商品成功')
    addDialogVisible.value = false
    loadProducts() // 重新加载商品列表
  } catch (error) {
    console.error('添加商品失败:', error)
    ElMessage.error(error?.response?.data?.message || '添加商品失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 获取农场信息和商品列表
const loadProducts = async () => {
  try {
    loading.value = true
    const farmId = route.params.farmId
    const currentUserId = parseInt(sessionStorage.getItem('userId'))
    
    console.log('开始加载数据, farmId:', farmId, 'currentUserId:', currentUserId)
    
    if (!farmId) {
      throw new Error('农场ID不能为空')
    }

    // 分开加载农场信息和商品列表
    try {
      // 获取农场基本信息
      const farmDetail = await getFarmDetail(farmId, currentUserId)
      console.log('获取到农场信息:', farmDetail)

      if (farmDetail && farmDetail.farmInfo) {
        farmName.value = farmDetail.farmInfo.farmName
        isOwner.value = currentUserId === farmDetail.farmInfo.userId
      } else {
        console.warn('获取农场信息失败:', farmDetail)
        farmName.value = '未知农场'
        isOwner.value = false
      }
    } catch (error) {
      console.error('获取农场信息出错:', error)
      farmName.value = '未知农场'
      isOwner.value = false
    }
    
    // 获取农场商品列表
    const productsRes = await getFarmProducts(farmId)
    console.log('获取到商品列表响应:', productsRes)
    
    if (Array.isArray(productsRes)) {
      // 转换数据结构
      products.value = productsRes.map(item => ({
        id: item.product.productId,
        name: item.product.productName,
        description: item.product.productDescription,
        price: item.product.price,
        stock: item.product.stock,
        images: item.images || [],
        categories: item.categories || [],
        createdAt: item.product.createdAt,
        updatedAt: item.product.updatedAt,
        status: item.product.status
      }))
      console.log('处理后的商品列表:', products.value)
    } else {
      console.warn('商品列表数据格式不正确:', productsRes)
      products.value = []
    }

    console.log('数据加载完成:', {
      farmName: farmName.value,
      isOwner: isOwner.value,
      productsCount: products.value.length
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败，请重试')
    products.value = []
    farmName.value = '加载失败'
    isOwner.value = false
  } finally {
    loading.value = false
  }
}

// 查看商品详情
const handleViewProduct = (product) => {
  console.log('点击查看商品:', product)
  console.log('当前路由参数:', route.params)
  const targetPath = `/product/${route.params.farmId}/${product.id}`
  console.log('准备跳转到:', targetPath)
  router.push(targetPath).then(() => {
    console.log('跳转成功')
  }).catch(err => {
    console.error('跳转失败:', err)
    ElMessage.error('页面跳转失败，请重试')
  })
}

// 编辑商品（修改库存）
const handleEditProduct = (product) => {
  stockDialog.form.productId = product.id
  stockDialog.form.stock = product.stock
  stockDialog.visible = true
}

// 删除商品
const handleDeleteProduct = async (product) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个商品吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deleteProduct(product.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 重新加载商品列表
      await loadProducts()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 获取主图
const getPrimaryImage = (images) => {
  if (!images || images.length === 0) {
    return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  }
  const primaryImage = images.find(img => img.isPrimary === 1)
  return primaryImage ? primaryImage.imageUrl : images[0].imageUrl
}

// 获取所有图片URL列表（用于预览）
const getImageUrls = (images) => {
  if (!images || images.length === 0) {
    return []
  }
  return images.map(img => img.imageUrl)
}

// 在setup中添加
const categories = ref([])

// 添加加载分类的方法
const loadCategories = async () => {
  try {
    const res = await getAllCategories()
    if (Array.isArray(res)) {
      categories.value = res
    } else {
      console.warn('分类列表数据格式不正确:', res)
      categories.value = []
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败，请重试')
    categories.value = []
  }
}

const stockDialog = reactive({
  visible: false,
  loading: false,
  form: {
    productId: null,
    stock: 0
  }
})

const handleStockDialogClose = () => {
  stockDialog.form.productId = null
  stockDialog.form.stock = 0
}

const handleUpdateStock = async () => {
  try {
    stockDialog.loading = true
    const { productId, stock } = stockDialog.form
    await updateProductStock(productId, stock)
    ElMessage.success('更新库存成功')
    stockDialog.visible = false
    // 重新加载商品列表
    loadProducts()
  } catch (error) {
    ElMessage.error('更新库存失败')
  } finally {
    stockDialog.loading = false
  }
}

onMounted(() => {
  loadProducts()
  loadCategories()
})
</script>

<style scoped>
.farm-products {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  flex: 0 0 auto;
}

.header-center {
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.logo-image {
  height: 40px;
  width: auto;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  margin: 80px auto 0;
  max-width: 1400px;
}

.content {
  margin-top: 20px;
}

.table-card {
  background-color: #fff;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.description-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.el-table {
  margin-top: 20px;
}

.el-button-group {
  display: flex;
  gap: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.product-uploader {
  :deep(.el-upload) {
    width: 100%;
  }
}

.mx-1 {
  margin: 0 4px;
}

.el-tag + .el-tag {
  margin-left: 4px;
}

.stock-form {
  padding: 20px;
}
</style> 